package com.test.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.test.entity.User;
import com.test.entity.Users;
import com.test.service.UserSercice;

import com.test.utils.TokenUtil;
import com.test.utils.UserLoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("api")
public class UserApi {
    @Autowired
    UserSercice userService;

    TokenUtil tokenService = new TokenUtil();
    //登录
    @PostMapping("/login")
    public Object login(@RequestBody User user){
        JSONObject jsonObject=new JSONObject();
        Users userForBase=userService.findByUsername(user);
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!userForBase.getU_password().equals(user.getUser_password())){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                String token = tokenService.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                Jedis jedis = new Jedis("localhost");
                Object obj = JSONArray.toJSON(userForBase);
                String json = obj.toString();
                jedis.set(token,json);
                return jsonObject;
            }
        }
    }
    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(HttpServletRequest request){
        String token = request.getHeader("token");
        Users user = TokenUtil.getUsersInfo(token);
        return "你已通过验证";
    }
}
